package com.example.sortlistview01.view;

import com.example.sortlistview01.activity.R;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

public class SideBarView extends View {
	// 26个字母
	public static String[] b = { "A", "B", "C", "D", "E", "F", "G", "H", "I",
			"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
			"W", "X", "Y", "Z", "#" };
	private Paint paint = new Paint();
	private TextView mTextDialog;
	private OnTouchSlideBarListener listener;

	public interface OnTouchSlideBarListener {
		void touchedIndex(int index);
	}

	public void setOnTouchSlideBarListener(OnTouchSlideBarListener listener) {
		this.listener = listener;
	}

	public void setTextView(TextView mTextDialog) {
		this.mTextDialog = mTextDialog;
	}

	public SideBarView(Context context) {
		this(context, null);
	}

	public SideBarView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public SideBarView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@SuppressLint("NewApi")
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		int action = event.getAction();
		float y = event.getY();
		final int index = (int) (y / getHeight() * b.length);// 点击y坐标所占总高度的比例*b数组的长度就等于点击b中的个数.

		switch (action) {
		case MotionEvent.ACTION_UP:
			setBackground(new ColorDrawable(0x00000000));
			mTextDialog.setVisibility(View.INVISIBLE);
			break;
		default:
			setBackgroundResource(R.drawable.sidebar_background);
			mTextDialog.setVisibility(View.VISIBLE);
			mTextDialog.setText(b[index]);
			if (listener != null) {
				listener.touchedIndex(index);
			}
			break;
		}
		return true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		paint.setColor(Color.rgb(33, 65, 98));
		paint.setTypeface(Typeface.DEFAULT_BOLD);
		paint.setAntiAlias(true);
		paint.setTextSize(20);
		float itemWidth = getWidth();
		float itemHeight = getHeight() / b.length;
		for (int i = 0; i < b.length; i++) {
			float posX = itemWidth / 2 - paint.measureText(b[i]) / 2;
			float posY = (i + 1) * itemHeight;
			canvas.drawText(b[i], posX, posY, paint);
		}
		super.onDraw(canvas);
	}

}
